<template>
	<view class="chat-container page-root" ref="page" @scroll="onScroll" :style="containerStyle" @touchstart="handlePageTouch">
		<!-- 使用picshow组件 -->
		<picshow :show="showImmersiveBackground"></picshow>
		
		<ai-chat ref="aiChat" @ai-message="handleAIMessage"
			@messages-updated="handleMessagesUpdated" @loading="handleLoading" @error="handleSSEError"></ai-chat>
		<conversation-summary ref="summarizer" :messages="summaryMessages" :modelId="modelManager.currentModel"
			@ai-message="handleAIMessage" @messages-updated="handleMessagesUpdated" @loading="handleLoading"
			@error="handleSSEError">
		</conversation-summary>

		<!-- iOS 18 风格导航栏 -->
		<view class="ios18-navbar" :class="{ 'immersive-navbar': showImmersiveBackground }" :style="{ paddingTop: statusBarHeight + 'px' }">
			<view class="navbar-content">
				<view class="navbar-left">
					<view class="nav-button" :class="{ 'immersive-button': showImmersiveBackground }" @click="goBack">
						<my-icon name="chevron-left" width="44rpx" height="44rpx" color="#ffffff" />
					</view>
				</view>
				<view class="navbar-center" @click="goToModelSelect">
					<view class="role-model-selector" :class="{ 'immersive-selector': showImmersiveBackground }">
						<text class="role-name">{{ roleName }}</text>
						<text class="model-name">({{ currentModelName }})</text>
					</view>
				</view>
				<view class="navbar-right">
					<view class="nav-button" :class="{ 'immersive-button': showImmersiveBackground }" @click="clearHistory">
						<my-icon name="delete" width="44rpx" height="44rpx" color="#ffffff" />
					</view>
				</view>
			</view>
		</view>

		<!-- 消息列表区域 -->
		<view id="messageList" class="message-list" :class="{ 'immersive-message-list': showImmersiveBackground }" :style="messageListStyle">
			<view class="messages-container">
				<view class="message" v-for="(message, index) in displayMessages" :key="message.id || index"
					:class="[message.type, { 'thinking': message.isThinking }, { 'immersive-message': showImmersiveBackground }]">
					<view class="message-content"
						:class="{ 'assistant-message': message.type === 'assistant', 'user-message': message.type === 'user', 'summary-message': message.type === 'summary', 'immersive-content': showImmersiveBackground }">
						<view v-if="message.type === 'assistant' && message.reasoning_content" class="reasoning-card"
							:class="{ expanded: message.isReasoningExpanded }">
							<view class="reasoning-header" @click="toggleReasoning(index)">
								<my-icon :name="message.isReasoningExpanded ? 'chevron-down' : 'chevron-right'"
									width="32rpx" height="32rpx" class="reasoning-icon" color="#ffffff" />
								<view class="reasoning-title">思考过程
									{{ message.isReasoningExpanded ? '(收起)' : '(展开)' }}</view>
							</view>
							<view class="reasoning-body" :class="{ collapsed: !message.isReasoningExpanded }">
								<view>{{ message.reasoning_content }}</view>
							</view>
						</view>
						<view v-if="message.type === 'summary'" class="summary-header">
							<my-icon name="chat" width="36rpx" height="36rpx" color="#ffffff" />
							<text class="summary-title">对话总结</text>
						</view>
						<view class="answer-content">
							<text class="message-text">{{ message.content }}</text>
							<view v-if="message.isThinking" class="thinking-dots">
								<text>.</text>
								<text>.</text>
								<text>.</text>
							</view>
						</view>
					</view>
					<!-- 消息操作按钮 -->
					<view class="message-actions" v-if="!message.isThinking">
						<view class="action-buttons">
							<view class="action-btn copy" @click="handleCopyMessage(message)">
								<my-icon name="copy" width="32rpx" height="32rpx" color="#ffffff" />
							</view>
							<view class="action-btn edit" v-if="message.type === 'user'"
								@click="handleEditMessage(message)">
								<my-icon name="edit" width="32rpx" height="32rpx" color="#ffffff" />
							</view>
							<view class="action-btn delete" @click="handleDeleteMessage(message)">
								<my-icon name="delete" width="32rpx" height="32rpx" color="#ffffff" />
							</view>
						</view>
					</view>
				</view>
			</view>
			<view style="height: 32rpx;"></view>
		</view>

		<!-- 操作抽屉 -->
		<view class="action-drawer" v-if="showActionDrawer" @click.self="showActionDrawer = false">
			<view class="action-drawer-panel" :class="{ 'drawer-show': showActionDrawer }">
				<view class="drawer-header">
					<text class="drawer-title">{{ actionDrawerTitle }}</text>
					<view class="drawer-close" @click="showActionDrawer = false">
						<my-icon name="close" width="40rpx" height="40rpx" color="#86868b" />
					</view>
				</view>
				<view class="action-drawer-content">
					<view class="action-item" @click="handleEditMessage" v-if="selectedMessage && selectedMessage.type === 'user'">
						<my-icon name="edit" width="40rpx" height="40rpx" color="#86868b" />
						<text class="action-item-text">编辑消息</text>
					</view>
					<view class="action-item" @click="handleCopyMessage">
						<my-icon name="copy" width="40rpx" height="40rpx" color="#86868b" />
						<text class="action-item-text">复制内容</text>
					</view>
					<view class="action-item delete" @click="handleDeleteMessage">
						<my-icon name="delete" width="40rpx" height="40rpx" color="#86868b" />
						<text class="action-item-text">删除消息</text>
					</view>
					<view class="action-item cancel" @click="showActionDrawer = false">
						<my-icon name="close" width="40rpx" height="40rpx" color="#86868b" />
						<text class="action-item-text">取消</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 编辑消息模态框 -->
		<view class="edit-modal-mask" v-if="showEditDrawer" @click.self="showEditDrawer = false">
			<view class="edit-modal-container" :class="{ 'modal-show': showEditDrawer }">
				<view class="modal-header">
					<text class="modal-title">编辑消息</text>
					<view class="modal-close" @click="showEditDrawer = false">
						<my-icon name="close" width="40rpx" height="40rpx" color="#86868b" />
					</view>
				</view>
				<view class="edit-modal-content">
					<textarea :adjust-position='false' class="edit-textarea" v-model="editingContent"
						placeholder="请输入新的消息内容" :maxlength="-1" :auto-height="true" :cursor-spacing="20" />
				</view>
				<view class="modal-footer">
					<view class="edit-actions">
						<my-button @click="showEditDrawer = false" type="default" size="mini" class="edit-btn cancel-btn">取消</my-button>
						<my-button @click="confirmEditMessage" type="primary" size="mini" class="edit-btn"
							:disabled="!editingContent.trim() || editingContent.trim() === (selectedMessage && selectedMessage.content)">保存</my-button>
					</view>
				</view>
			</view>
		</view>

		<!-- iOS 18 风格输入区域 -->
		<view class="ios18-input-container" :class="{ 'immersive-input': showImmersiveBackground }">
			<!-- 未激活状态的输入提示区域 -->
			<view v-if="!isInputActive" class="input-wrapper" :class="{ 'immersive-wrapper': showImmersiveBackground }" @click="activateInput">
				<view class="inactive-input-box">
					<text class="input-placeholder">输入消息...</text>
				</view>
				<view class="send-button-wrapper">
					<my-button disabled class="ios18-send-btn" type="primary" size="mini">
						<my-icon name="send" width="36rpx" height="36rpx" color="#000000" />
					</my-button>
				</view>
			</view>
			
			<!-- 激活状态的输入区域 -->
			<view v-if="isInputActive" class="input-wrapper active-input-wrapper" :class="{ 'immersive-wrapper': showImmersiveBackground }" 
				:style="inputContainerStyle" @touchstart.stop>
				<textarea :key="inputMessagekey" :auto-height="true" @input="handleInput" placeholder="输入消息..."
					confirm-type="send" @confirm="sendMessage" :rows="1" :maxrows="3" class="ios18-input-box" :adjust-position='false'
					:show-confirm-bar="false" :cursor-spacing="10" :auto-focus="true" @blur="handleInputBlur" />
				<view class="send-button-wrapper" :class="{ 'send-active': inputMessage.trim() }">
					<my-button @click="sendMessage" :disabled="isLoading || !inputMessage.trim()" class="ios18-send-btn"
						type="primary" size="mini">
						<my-icon name="send" width="36rpx" height="36rpx" color="#000000" />
					</my-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import roleManager from '@/store/role.js'
	import modelManager from '@/store/model.js'
	import settingsManager from '@/store/settings.js'
	import { getPic } from '@/utils/img.js'
	import Picshow from '@/components/picshow/picshow.vue'
	import { MessageStorage, MessageType } from '@/store/message-storage.js'

	// 消息前缀
	const CHAT_HISTORY_PREFIX = 'CHAT_';
	const MAX_HISTORY_LENGTH = 50;


	export default {
		components: {
			Picshow
		},
	
		data() {
			return {
				roleId: '',
				roleName: '',
				roleAvatar: '',
				rolePrompt: '',
				role: null, // 添加role对象，初始为null
				inputMessage: '',
				inputMessagekey: 0,
				messages: [],
				isLoading: false,
				retryCount: 0,
				maxRetries: 3,
				statusBarHeight: 0,
				navbarHeight: 0,
				isAtBottom: true,
				showActionDrawer: false,
				selectedMessage: null,
				actionDrawerTitle: '消息操作',
				showEditDrawer: false,
				editingContent: '',
				summaryMessages: [],
				modelManager,
				currentModelId: '',
				// 沉浸模式相关
				showImmersiveBackground: false,
				// 样式相关
				containerStyle: {
					backgroundColor: 'rgb(18, 18, 20)'
				},
				messageListStyle: {
					backgroundColor: 'rgb(18, 18, 20)'
				},
				isInputActive: false,
				jianpanHeight: 0,
				sysInfo: uni.getSystemInfoSync(),
				// 消息存储实例
				messageStorage: new MessageStorage(CHAT_HISTORY_PREFIX, MAX_HISTORY_LENGTH)
			}
		},

		computed: {
			// 获取当前模型名称
			currentModelName() {
				const model = modelManager.models.find(m => m.id === this.currentModelId);
				return model ? model.name : '未知模型';
			},
			
			// 根据沉浸模式状态决定显示哪些消息
			displayMessages() {
				// 如果开启了沉浸模式，只显示最新的一条消息
				if (this.showImmersiveBackground) {
					// 如果有消息，返回最后一条
					if (this.messages.length > 0) {
						return [this.messages[this.messages.length - 1]];
					}
					return []; // 没有消息时返回空数组
				}
				// 未开启沉浸模式，显示所有消息
				return this.messages;
			},
			inputContainerStyle() {
				if (this.isInputActive) {
					return {
						position: 'fixed',
						bottom: `${this.jianpanHeight}px`,
						left: '16px',
						right: '16px',
						width: 'auto',
						zIndex: 101
					};
				}
				return {};
			},
		},

		watch: {
			// 监听模型变化
			'modelManager.currentModel': {
				handler(newModelId) {
					if (newModelId !== this.currentModelId) {
						this.currentModelId = newModelId;
						this.handleModelChanged();
					}
				},
				immediate: true
			}
		},

		onLoad(options) {
			// 获取状态栏高度
			this.statusBarHeight = this.sysInfo.statusBarHeight;
			
			// 获取角色信息
			if (options.id) {
				this.roleId = options.id;
				const role = roleManager.getRoleByIdSync(this.roleId);
				if (role) {
					this.roleName = role.name;
					this.roleAvatar = role.avatar;
					this.rolePrompt = role.prompt;
					
					// 加载历史消息
					this.loadChatHistory();
				}
			}

			// 获取当前模型ID
			this.currentModelId = modelManager.currentModel;

			// 检查是否启用沉浸式背景
			this.showImmersiveBackground = settingsManager.getSettings().enableImmersiveMode;

			// 设置CSS变量
			// #ifdef H5
			document.documentElement.style.setProperty('--status-bar-height', `${this.statusBarHeight}px`);
			document.documentElement.style.setProperty('--navbar-height', `${this.statusBarHeight + 56}px`);
			// #endif

			// #ifndef H5
			// App环境下通过类名方式设置
			this.navbarHeight = this.statusBarHeight + 56;
			// #endif

			// 在页面加载完成后滚动到底部
			this.$nextTick(() => {
				this.scrollToBottom(false);
			});

			// 设置当前模型ID
			this.currentModelId = modelManager.currentModel;
			
			// 添加SSE关闭事件监听
			uni.$on('sse-closed', this.handleSSEClosed);
			
			// 添加设置变更事件监听
			uni.$on('settingsChange', this.handleSettingsChange);
			
			// 检查是否开启沉浸模式
			this.checkImmersiveMode();

			// #ifndef H5
			uni.onKeyboardHeightChange(this.keyBodyHeightWatch);
			// #endif
		},

		onUnload() {
			// 清理事件监听
			uni.$off('sse-closed', this.handleSSEClosed);
			uni.$off('settingsChange', this.handleSettingsChange);
			
			// 保存聊天历史（确保在退出页面时保存所有消息）
			console.log('[聊天] 页面卸载，保存聊天历史');
			this.saveChatHistory();
			
			// 清理背景切换定时器
			this.clearBackgroundTimer();

			// #ifndef H5
			uni.offKeyboardHeightChange(this.keyBodyHeightWatch);
			// #endif
		},

		onShow() {
			// 检查角色是否存在，如果不存在则重新加载
			this.checkRoleExists();
			
			// 检查并更新当前模型信息
			if (this.currentModelId !== modelManager.currentModel) {
				this.currentModelId = modelManager.currentModel;
				this.handleModelChanged();
			}
			
			// 检查沉浸模式状态
			this.checkImmersiveMode();

			// 监听键盘高度变化
			uni.onKeyboardHeightChange(res => {
				this.jianpanHeight = res.height;
			});
		},

		onHide() {
			// 移除键盘高度监听
			uni.offKeyboardHeightChange();
		},

		methods: {
			// 检查角色是否存在
			async checkRoleExists() {
				try {
					// 使用roleManager获取角色
					const result = await roleManager.getRoleById(this.roleId);
					
					if (result && result.errCode === 0 && result.data) {
						// 更新角色信息（以防角色被编辑）
						const role = result.data;
						this.role = role; // 保存完整的role对象
						this.roleName = role.name;
						this.roleAvatar = role.avatar;
						this.rolePrompt = role.prompt;
					} else {
						console.warn('[聊天] 角色不存在，可能已被删除');
						// 如果角色不存在，返回上一页
						uni.showToast({
							title: '角色不存在，可能已被删除',
							icon: 'none',
							duration: 2000
						});
						setTimeout(() => uni.navigateBack(), 2000);
					}
				} catch (error) {
					console.error('[聊天] 检查角色异常:', error);
					uni.showToast({
						title: '获取角色信息失败',
						icon: 'none',
						duration: 2000
					});
				}
			},
			
			// 加载角色信息
			async loadRoleInfo() {
				try {
					// 显示加载中
					uni.showLoading({
						title: '加载中...'
					});
					
					// 使用roleManager获取角色信息
					const result = await roleManager.getRoleById(this.roleId);
					
					if (result.errCode === 0 && result.data) {
						this.role = result.data;
						this.roleName = this.role.name;
						this.rolePrompt = this.role.prompt;
						
						// 如果角色有打招呼消息，添加到消息列表
						if (this.role.greeting) {
							this.messages.push({
								id: Date.now().toString(),
								type: MessageType.ASSISTANT,
								content: this.role.greeting,
								timestamp: new Date().toISOString()
							});
						}
						
						// 隐藏加载中
						uni.hideLoading();
					} else {
						console.error('[聊天页面] 获取角色失败:', result.errMsg);
						uni.hideLoading();
						
						// 显示错误提示
						uni.showModal({
							title: '角色不存在',
							content: '无法找到该角色信息，可能已被删除或未正确同步。是否返回上一页？',
							confirmText: '返回',
							cancelText: '留在此页',
							success: (res) => {
								if (res.confirm) {
									uni.navigateBack();
								} else {
									// 用户选择留在此页，尝试重新加载
									setTimeout(() => {
										this.loadRoleInfo();
									}, 1000);
								}
							}
						});
					}
				} catch (error) {
					console.error('[聊天页面] 加载角色异常:', error);
					uni.hideLoading();
					
					// 显示错误提示
					uni.showModal({
						title: '加载失败',
						content: '加载角色信息时出现错误，请检查网络连接后重试。',
						showCancel: false,
						success: () => {
							uni.navigateBack();
						}
					});
				}
			},

			// 获取最后一条消息
			getLastMessage() {
				return this.messages.length > 0 ? this.messages[this.messages.length - 1] : null;
			},

			// 查找最后一条用户消息
			findLastUserMessage() {
				for (let i = this.messages.length - 1; i >= 0; i--) {
					if (this.messages[i].type === MessageType.USER) {
						return this.messages[i];
					}
				}
				return null;
			},

			// 获取最后一条总结消息的索引
			findLastSummaryIndex() {
				for (let i = this.messages.length - 1; i >= 0; i--) {
					if (this.messages[i].type === 'summary') {
						return i;
					}
				}
				return -1; // 没有找到总结消息
			},

			// 获取最后一条总结之后的消息
			getMessagesAfterLastSummary() {
				const lastSummaryIndex = this.findLastSummaryIndex();

				// 如果找到了总结消息，返回其后的所有消息
				if (lastSummaryIndex !== -1) {
					console.log('[消息处理] 找到最后一条总结消息，索引:', lastSummaryIndex);
					return this.messages.slice(lastSummaryIndex + 1);
				}

				// 如果没有找到总结消息，返回所有消息
				console.log('[消息处理] 未找到总结消息，使用所有消息');
				return this.messages;
			},

			// 获取已完成的消息列表（用于发送给AI）
			getCompletedMessages() {
				// 获取最后一条总结消息
				const lastSummaryIndex = this.findLastSummaryIndex();
				const lastSummaryMessage = lastSummaryIndex !== -1 ? this.messages[lastSummaryIndex] : null;

				// 获取最后一条总结之后的消息
				const relevantMessages = this.getMessagesAfterLastSummary();

				// 准备API消息数组
				let apiMessages = [];

				// 如果存在上一条总结，将其添加到API消息的开头
				if (lastSummaryMessage) {
					console.log('[消息处理] 包含上一条总结消息');
					apiMessages.push({
						role: 'assistant',
						content: `上一次对话总结：${lastSummaryMessage.content}`
					});
				}

				// 过滤出已完成的消息并转换为API格式
				const conversationMessages = relevantMessages
					.filter(msg => !msg.isThinking && msg.content && msg.content.trim() !== '')
					.map(msg => ({
						role: msg.type === MessageType.USER ? 'user' : 'assistant',
						content: msg.content
					}));

				// 合并总结消息和对话消息
				apiMessages = apiMessages.concat(conversationMessages);

				console.log('[消息处理] 总消息数量:', apiMessages.length, lastSummaryMessage ? '(包含总结)' : '(无总结)');

				return apiMessages;
			},

			// 检查并生成对话总结
			async checkAndGenerateSummary() {
				try {
					// 获取设置中的总结阈值（轮数）
					const summaryThreshold = settingsManager.summaryThreshold || 10; // 默认10轮对话

					console.log('[总结] 开始检查是否需要生成总结, 轮数阈值:', summaryThreshold);

					// 获取最后一条总结消息
					const lastSummaryIndex = this.findLastSummaryIndex();
					const lastSummaryMessage = lastSummaryIndex !== -1 ? this.messages[lastSummaryIndex] : null;

					// 获取最后一条总结之后的消息
					const messagesAfterSummary = this.getMessagesAfterLastSummary();

					// 过滤出有效的用户和助手消息（排除思考中和总结类型的消息）
					const validMessages = messagesAfterSummary.filter(msg =>
						!msg.isThinking &&
						msg.content &&
						msg.content.trim() !== '' &&
						(msg.type === MessageType.USER || msg.type === MessageType.ASSISTANT) &&
						msg.type !== 'summary'
					);

					// 计算对话轮数（一问一答为一轮）
					// 首先按照类型分组消息
					const userMessages = validMessages.filter(msg => msg.type === MessageType.USER);
					const assistantMessages = validMessages.filter(msg => msg.type === MessageType.ASSISTANT);

					// 对话轮数取决于用户消息和AI消息中数量较少的那个
					const conversationTurns = Math.min(userMessages.length, assistantMessages.length);
					// 如果有未配对的用户消息（用户发了问题但AI还没回答），也算作半轮
					const hasUnpairedUserMessage = userMessages.length > assistantMessages.length;

					console.log('[总结] 最后一条总结后的有效对话轮数:', conversationTurns, hasUnpairedUserMessage ? '(有未配对的用户消息)' :
					'');

					// 检查对话轮数是否超过阈值
					if (conversationTurns >= summaryThreshold) {
						console.log('[总结] 对话轮数已超过阈值, 开始生成总结');

						try {
							// 显示正在生成总结提示
							uni.showLoading({
								title: '正在生成对话总结...'
							});

							// 准备API消息数组
							let apiMessages = [];

							// 如果存在上一条总结，将其添加到API消息的开头
							if (lastSummaryMessage) {
								console.log('[总结] 包含上一条总结消息');
								apiMessages.push({
									role: 'assistant',
									content: `上一次总结内容：${lastSummaryMessage.content}`,
									type: 'context'
								});
							}

							// 添加当前需要总结的消息
							apiMessages = apiMessages.concat(validMessages.map(msg => ({
								role: msg.type === MessageType.USER ? 'user' : 'assistant',
								content: msg.content
							})));

							console.log('[总结] 调用总结组件生成总结, 消息数量:', apiMessages.length);

							// 设置总结消息并调用总结组件生成总结
							this.summaryMessages = apiMessages;

							// 确保组件已经渲染并且引用可用
							this.$nextTick(() => {
								// 添加安全检查，确保summarizer组件存在
								if (this.$refs.summarizer) {
									// 重置总结组件状态
									if (typeof this.$refs.summarizer.reset === 'function') {
										console.log('[总结] 重置总结组件状态');
										this.$refs.summarizer.reset();
									}

									console.log('[总结] 调用总结组件生成总结');
									this.$refs.summarizer.generateSummary();
								} else {
									console.error('[总结] 总结组件引用不可用');
									uni.hideLoading();
									uni.showToast({
										title: '总结组件未就绪',
										icon: 'none'
									});
								}
							});

							return true;
						} catch (error) {
							console.error('[总结] 生成对话总结失败:', error);
							uni.hideLoading();
							uni.showToast({
								title: '生成对话总结失败',
								icon: 'none'
							});

							return false;
						}
					} else {
						console.log('[总结] 对话轮数未超过阈值, 不生成总结');
					}
				} catch (err) {
					console.error('[总结] 检查总结过程出错:', err);
				}

				return false;
			},

			// 处理AI消息流式更新
			handleAIMessage(delta) {
				// 检查是否是总结消息
				if (delta.type === 'summary') {
					// 处理总结消息
					console.log('[总结] 收到总结消息更新');

					// 查找或创建总结消息
					let summaryMessage = this.getLastMessage();
					if (!summaryMessage || summaryMessage.type !== 'summary') {
						// 创建新的总结消息
						summaryMessage = {
							type: 'summary',
							content: '',
							id: Date.now().toString(),
							timestamp: new Date().toISOString()
						};

						// 添加到消息列表
						this.messages.push(summaryMessage);
					}

					// 更新总结内容
					if (delta.content) {
						const index = this.messages.findIndex(m => m.id === summaryMessage.id);
						if (index !== -1) {
							const updatedContent = (this.messages[index].content || '') + delta.content;
							this.$set(this.messages[index], 'content', updatedContent);
						}
						this.scrollToBottom(false);
					}

					return;
				}

				// 处理普通AI消息
				const currentMsg = this.getLastMessage();
				if (!currentMsg || currentMsg.type !== MessageType.ASSISTANT) return;

				// 更新消息内容
				const index = this.messages.findIndex(m => m.id === currentMsg.id);
				if (index !== -1) {
					let updates = {};

					// 更新推理内容
					if (delta.reasoning_content) {
						updates.reasoning_content = (currentMsg.reasoning_content || '') + delta.reasoning_content;
					}

					// 更新消息内容
					if (delta.content) {
						// 清理内容中的[DONE]标记
						let cleanContent = delta.content.replace(/\[DONE\]/g, '');
						updates.content = (currentMsg.content || '') + cleanContent;
					}

					// 应用更新
					if (Object.keys(updates).length > 0) {
						Object.keys(updates).forEach(key => {
							this.$set(this.messages[index], key, updates[key]);
						});
						this.scrollToBottom(false);
					}
				}
			},

			// 处理消息更新
			handleMessagesUpdated(messages) {
				// 检查是否有总结类型的消息
				const hasSummaryMessage = messages.some(msg => msg.type === 'summary');

				if (hasSummaryMessage && messages.length > 0) {
					const lastMessage = messages[messages.length - 1];
					if (lastMessage.role === 'assistant' && lastMessage.content) {
						console.log('[总结] 总结生成完成');

						// 隐藏加载提示
						uni.hideLoading();

						// 查找最后一条总结消息
						const lastSummaryMsg = this.getLastMessage();
						if (lastSummaryMsg && lastSummaryMsg.type === 'summary') {
							// 更新现有总结消息
							const index = this.messages.findIndex(m => m.id === lastSummaryMsg.id);
							if (index !== -1) {
								this.$set(this.messages[index], 'content', lastMessage.content);
								this.$set(this.messages[index], 'isThinking', false);
							}
						} else {
							// 添加新的总结消息
							this.messages.push({
								type: 'summary',
								content: lastMessage.content,
								id: Date.now().toString(),
								timestamp: new Date().toISOString()
							});
						}

						// 重置总结组件状态
						if (this.$refs.summarizer && typeof this.$refs.summarizer.reset === 'function') {
							console.log('[总结] 总结完成后重置总结组件状态');
							this.$refs.summarizer.reset();
						}

						// 滚动到底部
						this.scrollToBottom(true);
						return;
					}
				}

				// 处理普通消息更新
				if (messages.length > 0) {
					const lastMessage = messages[messages.length - 1];
					if (lastMessage.role === 'assistant' && lastMessage.content) {
						const currentMsg = this.getLastMessage();
						if (currentMsg && currentMsg.type === MessageType.ASSISTANT) {
							const index = this.messages.findIndex(m => m.id === currentMsg.id);
							if (index !== -1) {
								this.$set(this.messages[index], 'content', lastMessage.content);
								this.$set(this.messages[index], 'isThinking', false);
							}
							this.scrollToBottom(true);
						}
					}
				}
			},

			// 处理加载状态变化
			handleLoading(loading) {
				this.isLoading = loading;

				// 如果加载结束，隐藏加载提示
				if (!loading) {
					uni.hideLoading();
				}
			},

			// 切换推理内容的展开/折叠状态
			toggleReasoning(index) {
				if (this.messages[index]) {
					this.$set(this.messages[index], 'isReasoningExpanded', 
						!this.messages[index].isReasoningExpanded);
				}
			},

			// 处理SSE错误
			handleSSEError(err) {
				console.error('[SSE] 错误:', err);

				// 处理SSE关闭事件
				if (err?.type === 'SSE_CLOSED') {
					// 使用专门的处理方法
					this.handleSSEClosed();
					return;
				}

				// 处理组件错误
				if (err?.type === 'COMPONENT_ERROR') {
					console.error('[组件错误]', err.message);
					uni.hideLoading();
					uni.showToast({
						title: err.message || '组件错误',
						icon: 'none'
					});
					return;
				}

				// 隐藏加载提示
				uni.hideLoading();

				if (this.retryCount < this.maxRetries) {
					this.retryCount++;
					uni.showToast({
						title: `连接失败，正在重试(${this.retryCount}/${this.maxRetries})`,
						icon: 'none',
						duration: 2000
					});

					setTimeout(() => {
						const lastUserMessage = this.findLastUserMessage();
						if (lastUserMessage) {
							this.retryMessage(lastUserMessage.content);
						}
					}, 2000);
				} else {
					this.isLoading = false;
					this.retryCount = 0;

					const lastMessage = this.getLastMessage();
					if (lastMessage && (!lastMessage.content || lastMessage.content.trim() === '')) {
						const index = this.messages.findIndex(m => m.id === lastMessage.id);
						if (index !== -1) {
							this.messages.splice(index, 1);
						}
					}

					uni.showModal({
						title: '连接失败',
						content: '是否重新发送消息？',
						success: (res) => {
							if (res.confirm) {
								const lastUserMessage = this.findLastUserMessage();
								if (lastUserMessage) {
									this.retryCount = 0;
									this.retryMessage(lastUserMessage.content);
								}
							} else {
								this.isLoading = false;
								this.retryCount = 0;
							}
						}
					});
				}
			},

			// 重试发送消息
			async retryMessage(content) {
				if (this.isLoading) return;

				const lastMessage = this.getLastMessage();
				let aiMessage;

				if (lastMessage && lastMessage.type === MessageType.ASSISTANT) {
					// 更新现有AI消息
					const index = this.messages.findIndex(m => m.id === lastMessage.id);
					if (index !== -1) {
						this.$set(this.messages[index], 'content', '');
						this.$set(this.messages[index], 'reasoning_content', '');
						this.$set(this.messages[index], 'isThinking', true);
						this.$set(this.messages[index], 'isReasoningExpanded', false);
						aiMessage = this.messages[index];
					}
				} else {
					// 创建新的AI消息
					aiMessage = {
						type: MessageType.ASSISTANT,
						content: '',
						isThinking: true,
						id: Date.now().toString(),
						timestamp: new Date().toISOString()
					};
					this.messages.push(aiMessage);
				}

				// 获取历史消息（使用最后一条总结之后的消息）
				const historyMessages = this.getCompletedMessages();
				console.log('[重试] 使用最后一条总结后的消息, 数量:', historyMessages.length);
				
				// 添加系统提示到历史记录
				const historyWithSystemPrompt = [
					{ role: 'system', content: this.rolePrompt || (this.role && this.role.prompt) || '' },
					...historyMessages
				];

				// 添加安全检查，确保aiChat组件存在
				if (this.$refs.aiChat) {
					// 发送消息
					this.$refs.aiChat.sendMessage(content, historyWithSystemPrompt, this.currentModelId);
				} else {
					console.error('[重试] AI聊天组件引用不可用');
					uni.showToast({
						title: '聊天组件未就绪',
						icon: 'none'
					});
					// 恢复消息状态
					if (aiMessage) {
						const index = this.messages.findIndex(m => m.id === aiMessage.id);
						if (index !== -1) {
							this.$set(this.messages[index], 'isThinking', false);
						}
					}
				}
			},

			// 滚动到底部
			scrollToBottom(withAnimation = true) {
				this.isAtBottom = true;

				setTimeout(() => {
					// #ifdef H5
					if (withAnimation) {
						window.scrollTo({
							top: document.body.scrollHeight,
							behavior: 'smooth'
						});
					} else {
						window.scrollTo(0, document.body.scrollHeight);
					}
					// #endif

					// #ifdef APP-PLUS || MP
					uni.pageScrollTo({
						scrollTop: 99999, // 使用一个足够大的值确保滚动到底部
						duration: withAnimation ? 300 : 0
					});
					// #endif
					
					// 再次尝试滚动，确保在内容渲染后滚动到底部
					setTimeout(() => {
						// #ifdef H5
						window.scrollTo({
							top: document.body.scrollHeight,
							behavior: withAnimation ? 'smooth' : 'auto'
						});
						// #endif

						// #ifdef APP-PLUS || MP
						uni.pageScrollTo({
							scrollTop: 999999,
							duration: withAnimation ? 300 : 0
						});
						// #endif
					}, 300);
				}, 100);
			},

			// 处理滚动事件
			onScroll(e) {
				// #ifdef H5
				// 获取页面滚动信息
				let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
				const windowHeight = window.innerHeight;
				const documentHeight = document.documentElement.scrollHeight;

				// 计算距离底部的距离
				const distanceFromBottom = documentHeight - (scrollTop + windowHeight);
				this.isAtBottom = distanceFromBottom < 150;
				// #endif

				// #ifdef APP-PLUS || MP
				// App环境下使用事件对象获取滚动位置
				scrollTop = e.detail ? e.detail.scrollTop : 0;

				// 获取页面和容器的高度信息
				const query = uni.createSelectorQuery();
				
				query.select('.page-root').boundingClientRect().exec(pageRes => {
					if (!pageRes || !pageRes[0]) return;

					query.select('.messages-container').boundingClientRect().exec(containerRes => {
						if (!containerRes || !containerRes[0]) return;

						const pageHeight = pageRes[0].height;
						const contentHeight = containerRes[0].height;

						// 计算距离底部的距离
						const distanceFromBottom = contentHeight - (scrollTop + pageHeight);
						this.isAtBottom = distanceFromBottom < 150;
					});
				});
				// #endif
			},

			// 发送消息
			sendMessage() {
				if (!this.inputMessage.trim() || this.isLoading) return;
				
				// 创建用户消息
				const userMessage = {
					id: Date.now().toString(),
					type: MessageType.USER,
					content: this.inputMessage.trim(),
					timestamp: new Date().toISOString()
				};
				
				// 添加用户消息到列表
				this.messages.push(userMessage);
				
				// 清空输入框
				const userContent = this.inputMessage.trim();
				this.inputMessage = '';
				this.inputMessagekey++;
				
				// 创建AI思考消息
				const aiMessage = {
					id: (Date.now() + 1).toString(),
					type: MessageType.ASSISTANT,
					content: '',
					isThinking: true,
					timestamp: new Date().toISOString()
				};
				
				// 添加AI消息到列表
				this.messages.push(aiMessage);
				
				// 主动隐藏键盘
				uni.hideKeyboard();
				
				// 取消输入框激活状态
				this.isInputActive = false;
				
				// 滚动到底部
				this.$nextTick(() => {
					this.scrollToBottom();
					
					// 获取历史消息
					const historyMessages = this.getCompletedMessages();
					
					// 添加系统提示到历史记录
					const historyWithSystemPrompt = [
						{ role: 'system', content: this.rolePrompt || (this.role && this.role.prompt) || '' },
						...historyMessages
					];
					
					// 调用AI聊天组件发送消息
					if (this.$refs.aiChat) {
						this.$refs.aiChat.sendMessage(userContent, historyWithSystemPrompt, this.currentModelId);
					} else {
						console.error('[发送] AI聊天组件引用不可用');
						uni.showToast({
							title: '聊天组件未就绪',
							icon: 'none'
						});
						
						// 移除思考中的消息
						const index = this.messages.findIndex(m => m.id === aiMessage.id);
						if (index !== -1) {
							this.messages.splice(index, 1);
						}
					}
				});
			},

			// 返回上一页
			goBack() {
				uni.navigateBack();
			},

			// 跳转到模型选择页面
			goToModelSelect() {
				uni.navigateTo({
					url: '/pages/model/select'
				});
			},

			// 清除聊天记录
			clearHistory() {
				if (!this.roleId) return;
				
				uni.showModal({
					title: '清除聊天记录',
						content: '确定要清除所有聊天记录吗？此操作不可恢复。',
						success: async (res) => {
							if (res.confirm) {
								try {
									// 使用messageStorage清除历史
									await this.messageStorage.clearMessages(this.roleId);
									
									// 清空当前消息列表
									this.messages = [];
									
									// 如果角色有打招呼消息，重新添加
									const role = roleManager.getRoleByIdSync(this.roleId);
									if (role && role.greeting) {
										this.messages.push({
											id: Date.now().toString(),
											type: MessageType.ASSISTANT,
											content: role.greeting,
											timestamp: new Date().toISOString()
										});
									}
									
									uni.showToast({
										title: '已清除聊天记录',
										icon: 'success'
									});
								} catch (error) {
									console.error('[聊天] 清除聊天记录失败:', error);
									uni.showToast({
										title: '清除失败',
										icon: 'none'
									});
								}
							}
						}
					});
			},

			// 处理编辑消息
			handleEditMessage(message) {
				this.selectedMessage = message;
				this.editingContent = message.content;
				this.showEditDrawer = true;
				this.showActionDrawer = false;
			},

			// 确认编辑消息
			confirmEditMessage() {
				if (!this.selectedMessage || !this.editingContent.trim()) return;
				
				const index = this.messages.findIndex(m => m.id === this.selectedMessage.id);
				if (index !== -1) {
					// 更新消息内容
					this.messages[index].content = this.editingContent.trim();
					
					// 删除该消息后的所有消息
					if (index < this.messages.length - 1) {
						this.messages.splice(index + 1);
					}
					
					// 准备编辑后的消息内容
					const editedContent = this.editingContent.trim();
					
					// 关闭编辑抽屉
					this.showEditDrawer = false;
					this.selectedMessage = null;
					this.editingContent = '';
					
					// 滚动到底部
					this.$nextTick(() => {
						this.scrollToBottom();
						
						// 触发AI回复
						this.retryMessage(editedContent);
					});
					
					// 保存更新后的消息历史
					this.saveChatHistory();
				} else {
					this.showEditDrawer = false;
					this.selectedMessage = null;
					this.editingContent = '';
				}
			},

			// 处理复制消息
			handleCopyMessage(message) {
				uni.setClipboardData({
					data: message.content,
					success: () => {
						uni.showToast({
							title: '已复制到剪贴板',
							icon: 'none'
						});
					}
				});
				this.showActionDrawer = false;
			},

			// 处理删除消息
			handleDeleteMessage(message) {
				const index = this.messages.findIndex(m => m.id === message.id);
				if (index !== -1) {
					this.messages.splice(index, 1);
					
					// 保存消息历史
					this.saveChatHistory();
				}
				this.showActionDrawer = false;
			},

			// 查找最后一条用户消息的索引
			findLastUserMessageIndex() {
				for (let i = this.messages.length - 1; i >= 0; i--) {
					if (this.messages[i].type === MessageType.USER) {
						return i;
					}
				}
				return -1;
			},

			// 处理模型变化
			handleModelChanged() {
				// 显示模型切换提示
				uni.showToast({
					title: `已切换到${this.currentModelName}`,
					icon: 'none',
					duration: 1500
				});

				// 如果有需要，这里可以添加其他模型切换后的处理逻辑
				// 例如：重置对话状态、更新UI等
			},

			// 处理SSE连接关闭事件
			handleSSEClosed() {
				console.log('[SSE] 连接已关闭');
				this.isLoading = false;
				this.retryCount = 0;

				// 获取最后一条消息
				const lastMessage = this.getLastMessage();

				// 首先确保消息不再处于思考状态
				if (lastMessage) {
					// 如果是空消息且处于思考状态，则删除
					if (lastMessage.isThinking && (!lastMessage.content || lastMessage.content.trim() === '')) {
						console.log('[SSE] 删除空的思考消息');
						this.removeMessage(lastMessage.id);
					}
					// 如果消息有内容并且处于思考状态，则更新状态
					else if (lastMessage.isThinking) {
						console.log('[SSE] 更新消息状态为完成');
						this.updateMessage(lastMessage.id, {
							isThinking: false,
							isReasoningExpanded: true // 自动展开推理内容
						});
					}
					// 即使消息已经完成，也记录日志
					else {
						console.log('[SSE] 消息已经是完成状态');
					}
				}

				// 检查是否已经在生成总结
				if (this.$refs.summarizer && this.$refs.summarizer.isLoading) {
					console.log('[SSE] 已经在生成总结中，不重复触发');
					return;
				}

				// 无论最后一条消息是否在思考状态，都检查是否需要生成总结
				console.log('[SSE] 连接关闭后检查是否需要生成总结');
				this.checkAndGenerateSummary();
			},

			// 处理输入事件
			handleInput(e) {
				this.inputMessage = e.detail.value;
			},

			// 检查是否开启沉浸模式
			async checkImmersiveMode() {
				// 添加更详细的日志输出
				console.log('[聊天页面] 检查沉浸模式状态:');
				console.log('[聊天页面] 登录状态:', settingsManager.isLoggedIn);
				console.log('[聊天页面] 高级设置解锁状态:', settingsManager.adultSettingUnlocked);
				console.log('[聊天页面] 沉浸模式设置值:', settingsManager._settings.immersiveMode);
				console.log('[聊天页面] 沉浸模式getter返回值:', settingsManager.immersiveMode);
				
				// 检查高级设置是否解锁
				if (!settingsManager.adultSettingUnlocked) {
					console.log('[聊天页面] 高级设置未解锁，无法开启沉浸模式');
					this.showImmersiveBackground = false;
					// 恢复原来的背景色
					this.containerStyle.backgroundColor = 'rgb(18, 18, 20)';
					this.messageListStyle.backgroundColor = 'rgb(18, 18, 20)';
					return;
				}
				
				// 检查是否开启沉浸模式
				if (settingsManager.immersiveMode) {
					console.log('[聊天页面] 沉浸模式已开启');
					this.showImmersiveBackground = true;
					
					// 设置透明背景
					this.containerStyle.backgroundColor = 'transparent';
					this.messageListStyle.backgroundColor = 'transparent';
				} else {
					console.log('[聊天页面] 沉浸模式未开启');
					this.showImmersiveBackground = false;
					// 恢复原来的背景色
					this.containerStyle.backgroundColor = 'rgb(18, 18, 20)';
					this.messageListStyle.backgroundColor = 'rgb(18, 18, 20)';
				}
			},
			
			// 处理设置变更事件
			handleSettingsChange(event) {
				// 如果是沉浸模式或高级设置解锁状态变更，重新检查沉浸模式
				if (event.type === 'immersiveMode' || event.type === 'adultSettingUnlocked') {
					console.log('[聊天页面] 设置变更:', event.type, event.value);
					this.checkImmersiveMode();
				}
			},
			activateInput() {
				this.isInputActive = true;
			},
			handleInputBlur() {
				// 使用更短的延迟确保键盘收起后再重置输入框状态
				setTimeout(() => {
					// 主动隐藏键盘
					uni.hideKeyboard();
					this.isInputActive = false;
				}, 50);
			},
			keyBodyHeightWatch(e) {
				this.jianpanHeight = e.height;
				if (this.jianpanHeight === 0 && this.isInputActive) {
					console.log('[键盘] 键盘高度为0，重置输入框状态');
					// 延迟一点时间后重置输入框状态，确保界面已经更新
					setTimeout(() => {
						this.isInputActive = false;
					}, 50);
				}
			},
			// 处理页面触摸事件
			handlePageTouch(e) {
				// 如果输入框处于激活状态，则取消激活
				if (this.isInputActive) {
					this.isInputActive = false;
				}
			},
			// 加载聊天历史
			async loadChatHistory() {
				try {
					if (!this.roleId) {
						console.error('[聊天] 加载历史消息失败: 未找到角色ID');
						return;
					}
					
					// 使用messageStorage获取历史消息
					const history = await this.messageStorage.getMessages(this.roleId);
					if (history && history.length > 0) {
						// 为每条消息添加处理推理展开状态的属性
						this.messages = history.map(msg => ({
							...msg,
							isReasoningExpanded: false
						}));
						console.log('[聊天] 已加载历史消息:', this.messages.length);
						
						// 首次加载后滚动到底部
						this.$nextTick(() => {
							console.log('[聊天] 首次加载历史消息后滚动到底部');
							this.scrollToBottom(false);
						});
					} else {
						console.log('[聊天] 没有历史消息，显示打招呼消息');
						// 如果没有历史消息且角色有打招呼消息，添加到消息列表
						const role = roleManager.getRoleByIdSync(this.roleId);
						if (role && role.greeting) {
							this.messages.push({
								id: Date.now().toString(),
								type: MessageType.ASSISTANT,
								content: role.greeting,
								timestamp: new Date().toISOString()
							});
							
							// 有打招呼消息也需要滚动到底部
							this.$nextTick(() => {
								console.log('[聊天] 显示打招呼消息后滚动到底部');
								this.scrollToBottom(false);
							});
						}
					}
				} catch (error) {
					console.error('[聊天] 加载历史消息失败:', error);
					this.messages = [];
				}
			},
			
			// 保存聊天历史
			async saveChatHistory() {
				if (!this.roleId) return;
				
				try {
					// 过滤出非思考中的消息
					const completedMessages = this.messages.filter(msg => !msg.isThinking);
					
					// 使用messageStorage保存历史消息
					await this.messageStorage.saveMessages(this.roleId, completedMessages);
					console.log('[聊天] 已保存历史消息:', completedMessages.length);
				} catch (error) {
					console.error('[聊天] 保存历史消息失败:', error);
				}
			},
			// 更新消息
			updateMessage(messageId, updates) {
				const index = this.messages.findIndex(msg => msg.id === messageId);
				if (index === -1) return null;

				// 更新本地消息
				const updatedMessage = {
					...this.messages[index],
					...updates
				};
				this.$set(this.messages, index, updatedMessage);

				return updatedMessage;
			},
			
			// 删除消息
			removeMessage(messageId) {
				const index = this.messages.findIndex(msg => msg.id === messageId);
				if (index !== -1) {
					this.messages.splice(index, 1);
					return true;
				}
				return false;
			},
		}
	}
</script>

<style>
	:root {
		--primary-color-rgb: 212, 165, 32;
		--text-color-rgb: 255, 255, 255;
		--border-color-rgb: 255, 255, 255;
		--card-bg-color-rgb: 44, 44, 46;
		--bg-color-rgb: 18, 18, 20;
		--nav-bg-color: rgba(18, 18, 20, 0.9);
		--text-on-primary-color: #000000;
		--text-secondary-color: #86868b;
		--card-bg-color: #2c2c2e;
		--border-color: rgba(255, 255, 255, 0.1);
		--input-bg-color: #3a3a3c;
	}

	.chat-container {
		position: relative;
		width: 100%;
		min-height: 100vh;
		background-color: transparent; /* 当开启沉浸模式时应该是透明的 */
		overflow-y: auto;
		font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, sans-serif;
		color: #ffffff;
	}
	
	/* 沉浸模式背景 */
	.immersive-background {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		z-index: 1; /* 改为1，使背景图片可见 */
		overflow: hidden;
		width: 100vw;
		height: 100vh;
	}
	
	.background-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
		position: absolute;
		top: 0;
		left: 0;
		transition: opacity 0.1s ease; /* 添加过渡效果 */
	}
	
	.background-overlay {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.4); /* 降低不透明度，使背景更清晰 */
		/* 移除毛玻璃效果 */
		/* backdrop-filter: blur(5px); */
		/* -webkit-backdrop-filter: blur(5px); */
	}
	
	/* 确保所有内容在背景之上 */
	.message-list, .ios18-navbar, .ios18-input-container {
		position: relative;
		z-index: 2; /* 提高到2，确保在背景之上 */
	}

	/* iOS 18 风格导航栏 */
	.ios18-navbar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		/* background-color: var(--nav-bg-color); */
		/* 恢复毛玻璃效果 */
		backdrop-filter: blur(10px);
		-webkit-backdrop-filter: blur(10px);
		z-index: 100; /* 保持较高的z-index */
		border-bottom: 0.5rpx solid rgba(255, 255, 255, 0.1);
		box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.2);
		transition: all 0.3s ease;
	}

	/* 沉浸模式下的导航栏样式 */
	.ios18-navbar.immersive-navbar {
		background-color: transparent;
		backdrop-filter: blur(5px);
		-webkit-backdrop-filter: blur(5px);
		border-bottom: none;
		box-shadow: none;
	}

	.navbar-content {
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 8px;
	}

	.navbar-left,
	.navbar-right {
		width: 44px;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.nav-button {
		width: 36px;
		height: 36px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 18px;
		background-color: rgba(255, 255, 255, 0.05);
		transition: all 0.2s ease;
	}

	/* 沉浸模式下的按钮样式 */
	.nav-button.immersive-button {
		background-color: rgba(0, 0, 0, 0.2);
		backdrop-filter: blur(5px);
		-webkit-backdrop-filter: blur(5px);
	}

	.nav-button:active {
		background-color: rgba(255, 255, 255, 0.1);
		transform: scale(0.95);
	}

	.navbar-center {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
		}

	.role-model-selector {
		display: flex;
		align-items: center;
		gap: 6px;
		padding: 6px 12px;
		border-radius: 16px;
		transition: background-color 0.2s ease;
	}

	/* 沉浸模式下的选择器样式 */
	.role-model-selector.immersive-selector {
		background-color: rgba(0, 0, 0, 0.2);
		backdrop-filter: blur(5px);
		-webkit-backdrop-filter: blur(5px);
		padding: 8px 16px;
	}

	.role-model-selector:active {
		background-color: rgba(255, 255, 255, 0.05);
	}

	.role-name {
		font-size: 18px;
		color: #ffffff;
		font-weight: 600;
		margin-right: 8px;
	}

	.model-name {
		font-size: 14px;
		color: #86868b;
		font-weight: 500;
	}

	/* 消息列表区域 */
	.message-list {
		width: 100%;
		margin-top: var(--navbar-height, 76px);
		margin-bottom: 120rpx;
		padding: 16rpx 32rpx;
		background-color: transparent; /* 改为透明背景 */
		z-index: 1;
		padding-bottom: 160rpx; /* 确保底部有足够空间 */
		transition: all 0.3s ease;
	}

	/* 沉浸模式下的消息列表样式 */
	.immersive-message-list {
		padding: 16rpx 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		min-height: 70vh;
	}

	/* 沉浸模式下的消息样式 */
	.message.immersive-message {
		margin-bottom: 0;
		width: 100%;
	}

	.message.immersive-message .message-content {
		max-width: 90%;
		margin: 0 auto;
	}

	/* 沉浸模式下的消息内容样式 */
	.message-content.immersive-content {
		background-color: rgba(41, 42, 46, 0.4);
		backdrop-filter: blur(5px);
		-webkit-backdrop-filter: blur(5px);
		border: 1px solid rgba(255, 255, 255, 0.1);
		box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
	}

	.message.assistant .message-content.immersive-content {
		border-radius: 16px;
		padding: 20rpx 40rpx;
	}

	.user-message.immersive-content {
		background-color: rgba(212, 165, 32, 0.6);
	}

	/* 消息容器 */
	.messages-container {
		display: flex;
		flex-direction: column;
		width: 100%;
		padding-bottom: 16rpx;
	}

	.message {
		display: flex;
		flex-direction: column;
		margin-bottom: 16rpx;
	}

	.message.user {
		align-items: flex-end;
	}

	.message.assistant {
		align-items: stretch;
		margin: 0 -16px;
	}

	.assistant-message {
		width: 100%;
		max-width: 100%;
		color: #ffffff;
		border-radius: 0;
		box-shadow: none;
		/* border-top: 1px solid rgba(255, 255, 255, 0.1); */
		/* border-bottom: 1px solid rgba(255, 255, 255, 0.1); */
		/* background-color: rgba(41, 42, 46, 0.6); */
		backdrop-filter: blur(5px);
		-webkit-backdrop-filter: blur(5px);
	}

	.user-message {
		max-width: 75%;
		background-color: rgba(212, 165, 32, 0.9);
		color: #000000;
		border-top-right-radius: 4rpx;
		border-radius: 20rpx;
		box-shadow: 0 2px 8px rgba(212, 165, 32, 0.3);
	}

	.summary-message {
		width: 100%;
		background-color: rgba(10, 132, 255, 0.2);
		border: 1rpx solid rgba(10, 132, 255, 0.4);
		border-radius: 16rpx;
		color: #ffffff;
		/* 恢复毛玻璃效果 */
		backdrop-filter: blur(5px);
		-webkit-backdrop-filter: blur(5px);
	}

	.message-content {
		border-radius: 20rpx;
		padding: 16rpx 24rpx;
		word-break: break-word;
		position: relative;
		transition: opacity 0.2s, transform 0.2s;
	}

	.message.assistant .message-content {
		border-radius: 0;
		/* padding: 12rpx 40rpx; */
	}

	.message.assistant .message-actions {
		padding: 0 40rpx;
	}

	.reasoning-card {
		border-radius: 12px;
		margin: 0 0 4px 0;
		overflow: hidden;
		border: 1px solid rgba(255, 255, 255, 0.1);
		background-color: rgba(58, 58, 60, 0.5);
    margin-bottom: -48rpx;
	}

	.reasoning-header {
		padding: 6px 12px;
		display: flex;
		align-items: center;
		cursor: pointer;
	}

	.reasoning-icon {
		transition: transform 0.3s;
	}

	.reasoning-title {
		font-size: 14px;
		color: #ffffff;
		font-weight: 500;
	}

	.reasoning-body {
		padding: 0 12px 6px;
		font-size: 14px;
		color: #86868b;
		transition: max-height 0.3s;
	}

	.collapsed {
		max-height: 0;
		padding: 0 12px;
		overflow: hidden;
	}

	.expanded .reasoning-body {
		max-height: 1000px;
	}

	.answer-content {
		margin-top: 4px;
	}

	.summary-header {
		display: flex;
		align-items: center;
		gap: 8rpx;
		margin-bottom: 8rpx;
	}

	.summary-title {
		font-size: 28rpx;
		font-weight: 500;
		color: #0a84ff;
	}

	/* iOS 18 风格输入区域 */
	.ios18-input-container {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 16px;
		background-color: rgba(18, 18, 20, 0.9);
		/* 恢复毛玻璃效果 */
		backdrop-filter: blur(10px);
		-webkit-backdrop-filter: blur(10px);
		display: flex;
		align-items: center;
		border-top: 1px solid rgba(255, 255, 255, 0.1);
		z-index: 100; /* 提高z-index确保在最上层 */
		box-shadow: 0 -8rpx 16rpx rgba(0, 0, 0, 0.3);
		/* #ifdef APP-PLUS */
		padding-bottom: calc(16px + constant(safe-area-inset-bottom));
		padding-bottom: calc(16px + env(safe-area-inset-bottom));
		/* #endif */
		transition: all 0.3s ease;
	}

	/* 沉浸模式下的输入容器样式 */
	.ios18-input-container.immersive-input {
		background-color: rgba(18, 18, 20, 0.4);
		backdrop-filter: blur(5px);
		-webkit-backdrop-filter: blur(5px);
		border-top: none;
		box-shadow: none;
		padding: 12px;
	}

	.input-wrapper {
		display: flex;
		align-items: flex-end;
		width: 100%;
		background-color: rgba(58, 58, 60, 0.9); /* 增加不透明度 */
		border-radius: 24px;
		padding: 8px 8px 8px 16px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
		transition: all 0.3s ease;
	}

	/* 沉浸模式下的输入框包装器样式 */
	.input-wrapper.immersive-wrapper {
		background-color: rgba(58, 58, 60, 0.5);
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}
	
	/* 未激活状态的输入框样式 */
	.inactive-input-box {
		flex: 1;
		min-height: 36px;
		font-size: 16px;
		line-height: 20px;
		color: #86868b;
		display: flex;
		align-items: center;
	}
	
	.input-placeholder {
		color: #86868b;
	}

	.ios18-input-box {
		flex: 1;
		/* min-height: 36px; */
		max-height: 120px;
		/* padding: 8px 0; */
		font-size: 16px;
		line-height: 20px;
		color: #ffffff;
		background-color: transparent;
	}

	/* 添加输入框占位符文本颜色样式 */
	.ios18-input-box::placeholder {
		color: #86868b;
	}

	.send-button-wrapper {
		margin-left: 8px;
		transition: transform 0.2s ease;
	}

	.send-active {
		transform: scale(1.05);
	}

	.ios18-send-btn {
		/* width: 36px; */
		/* height: 36px; */
		width: 38rpx !important;
		height: 38rpx !important;
		border-radius: 18rpx !important;
		padding: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: transform 0.2s ease;
		background-color: #d4a520 !important;
	}

	.send-button-wrapper.send-active .ios18-send-btn {
		transform: scale(1.05);
	}

	/* 思考动画 */
	.thinking .message-content {
		position: relative;
	}

	.thinking-dots {
		display: flex;
		padding: 5px 0;
	}

	.thinking-dots text {
		font-size: 24px;
		line-height: 1;
		animation: thinking-animation 1.4s infinite;
		margin-right: 2px;
	}

	.thinking-dots text:nth-child(2) {
		animation-delay: 0.2s;
	}

	.thinking-dots text:nth-child(3) {
		animation-delay: 0.4s;
	}

	@keyframes thinking-animation {

		0%,
		60%,
		100% {
			transform: translateY(0);
			opacity: 0.3;
		}

		30% {
			transform: translateY(-4px);
			opacity: 1;
		}
	}

	.thinking .assistant-message {
		opacity: 0.7;
	}

	/* 消息操作按钮样式 */
	.message-actions {
		display: flex;
		justify-content: flex-end;
		margin-top: 4px;
		padding: 0 4px;
		opacity: 0.85;
	}

	.message.user .message-actions {
		justify-content: flex-end;
	}

	.message.assistant .message-actions {
		justify-content: flex-start;
	}

	.action-buttons {
		display: flex;
		gap: 8px;
		height: 28px;
	}

	.action-btn {
		width: 28px;
		height: 28px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 14px;
		background-color: rgba(255, 255, 255, 0.05);
		box-shadow: none;
		transition: all 0.2s ease;
	}

	.action-btn:active {
		transform: scale(0.92);
		opacity: 0.6;
		background-color: rgba(255, 255, 255, 0.1);
	}

	/* 操作抽屉样式 */
	.action-drawer {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.7);
		z-index: 1000;
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
	}

	.action-drawer-panel {
		background-color: #2c2c2e;
		border-radius: 24rpx 24rpx 0 0;
		padding: 20rpx 0;
		transform: translateY(100%);
		transition: transform 0.3s ease-out;
	}

	.drawer-show {
		transform: translateY(0);
	}

	.drawer-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 32rpx;
		border-bottom: 1px solid rgba(255, 255, 255, 0.1);
	}

	.drawer-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #ffffff;
	}

	.drawer-close {
		padding: 16rpx;
		margin: -16rpx;
	}

	.action-drawer-content {
		padding: 16rpx 0;
	}

	.action-item {
		display: flex;
		align-items: center;
		padding: 24rpx 32rpx;
		transition: background-color 0.2s;
	}

	.action-item:active {
		background-color: rgba(255, 255, 255, 0.05);
	}

	.action-item-text {
		margin-left: 16rpx;
		font-size: 32rpx;
		color: #ffffff;
	}

	.action-item.delete .action-item-text {
		color: #ff453a;
	}

	/* 编辑模态框样式 */
	.edit-modal-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.7);
		backdrop-filter: blur(4rpx);
		-webkit-backdrop-filter: blur(4rpx);
		z-index: 1000;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.edit-modal-container {
		width: 90%;
		background-color: #2c2c2e;
		border-radius: 24rpx;
		transform: scale(0.9);
		opacity: 0;
		transition: all 0.3s ease-out;
		box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.3);
	}

	.modal-show {
		transform: scale(1);
		opacity: 1;
	}

	.modal-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 32rpx;
		border-bottom: 1px solid rgba(255, 255, 255, 0.1);
	}

	.modal-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #ffffff;
	}

	.modal-close {
		padding: 16rpx;
		margin: -16rpx;
	}

	.modal-footer {
		padding: 24rpx 32rpx;
		border-top: 1px solid rgba(255, 255, 255, 0.1);
	}

	.edit-modal-content {
		padding: 32rpx;
	}

	.edit-textarea {
		width: 100%;
		min-height: 240rpx;
		background-color: #3a3a3c;
		border-radius: 16rpx;
		padding: 24rpx;
		font-size: 28rpx;
		color: #ffffff;
		border: 1px solid rgba(255, 255, 255, 0.1);
	}

	.edit-textarea::placeholder {
		color: #86868b;
	}

	.edit-actions {
		display: flex;
		justify-content: flex-end;
		gap: 24rpx;
	}

	.edit-btn {
		min-width: 160rpx;
		height: 80rpx;
		border-radius: 40rpx;
		font-size: 28rpx;
		font-weight: 500;
		padding: 0 40rpx;
	}

	.cancel-btn {
		background-color: rgba(255, 255, 255, 0.05) !important;
		color: #ffffff !important;
		border: 1px solid rgba(255, 255, 255, 0.1);
	}

	/* 动画相关样式 */
	.drawer-enter-active,
	.drawer-leave-active,
	.modal-enter-active,
	.modal-leave-active {
		transition: all 0.3s ease-out;
	}

	.drawer-enter-from,
	.drawer-leave-to {
		transform: translateY(100%);
	}

	.modal-enter-from,
	.modal-leave-to {
		transform: scale(0.9);
		opacity: 0;
	}

	/* 激活状态的输入框包装器样式 */
	.active-input-wrapper {
		position: fixed;
		z-index: 101;
		background-color: rgba(58, 58, 60, 0.9);
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
	}
	
	.active-input-wrapper.immersive-wrapper {
		background-color: rgba(58, 58, 60, 0.5);
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}
</style>